package com.xw.utils;

import com.xw.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description: 文件保存工具类
 * @Author: y
 * @CreateDate: 2020-07-27 15:19
 * @Version: 1.0
 */
@Slf4j
public class FileUtil {
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    private static Random r = new Random();
    //    private static String basePath = Objects.requireNonNull(Thread.currentThread().getContextClassLoader().getResource("")).getPath();
//    private static SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    private static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

    /**
     * 图片类型
     */
    private static final List<String> fileTypes = new ArrayList<String>();

    static {
        fileTypes.add(".jpg");
        fileTypes.add(".jpeg");
        fileTypes.add(".bmp");
        fileTypes.add(".gif");
        fileTypes.add(".png");
    }

    public static ResultVO<?> saveFile(MultipartFile file, HttpServletRequest request) {
        if (file != null) {
            String compression = request.getParameter("compression");
            String frame = request.getParameter("frame");

            String targetAddr = PathUtil.getImgPath(sdf.format(new Date()));
            // 获取不重复的随机名
            String realFileName = getRandomFileName();
            // 获取文件的扩展名如png,jpg等
            String extension = getFileExtension(Objects.requireNonNull(file.getOriginalFilename()));
//            if (!fileTypes.contains(extension.toLowerCase())) {
//                return ResultVOUtil.error(ResultEnum.IMG_TYPE_ERR);
//            }
            // 如果目标路径不存在，则自动创建
            makeDirPath(targetAddr);
            // 获取文件存储的相对路径(带文件名)
            String relativeAddr = targetAddr + realFileName + extension;
            // 获取文件要保存到的目标路径
            File dest = new File(PathUtil.getImgBasePath() + relativeAddr);
            log.debug("current complete addr is :" + PathUtil.getImgBasePath() + relativeAddr);
            try {
                file.transferTo(dest);
                if (ObjectUtils.isEmpty(compression)) {
                    FileUtil.compression(dest, 500, "K");
                }
                //是否视频帧图片
//                if (!ObjectUtils.isEmpty(frame) && "true".equals(frame)) {
//                    String videoFrame = VideoFrameUtil.grabberVideoFramerLocal(PathUtil.getImgBasePath() + relativeAddr, 5);
//                    return ResultVOUtil.success(relativeAddr + "," + videoFrame);
//                }
            } catch (IOException e) {
                log.error("file save err : {}", e.toString());
                e.printStackTrace();
            }

            return ResultVOUtil.success(relativeAddr);
        }
        return ResultVOUtil.fail();

    }

    /**
     * 生成随机文件名，当前年月日小时分钟秒钟+五位随机数
     *
     * @return 随机
     */
    private static String getRandomFileName() {
        // 获取随机的五位数
        int ranNum = r.nextInt(89999) + 10000;
        LocalDateTime localDateTime = LocalDateTime.now();
        return localDateTime.format(dtf) + ranNum;
    }


    public static void compression(File file, int size, String unit) throws IOException {
        if (!checkFileSize(file.length(), size, unit)) {
            Thumbnails.of(file).scale(0.5f).toFile(file);
            compression(file, size, unit);
        }
    }

    private static boolean checkFileSize(Long len, int size, String unit) {
        double fileSize = 0;
        switch (unit.toUpperCase()) {
            case "B":
                fileSize = (double) len;
                break;
            case "K":
                fileSize = (double) len / 1024;
                break;
            case "M":
                fileSize = (double) len / 1048576;
                break;
            case "G":
                fileSize = (double) len / 1073741824;
                break;
            default:
                break;
        }
        return !(fileSize > size);
    }

    /**
     * 获取输入文件流的扩展名
     *
     * @return 后缀
     */
    private static String getFileExtension(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }


    /**
     * 获取htmlStr img路径
     *
     * @param htmlStr
     * @return
     */
//    public static List<String> getImgStr(String htmlStr) {
//        List<String> pics = new ArrayList<String>();
//        String img = "";
//        Pattern p_image;
//        Matcher m_image;
//        //     String regEx_img = "<img.*src=(.*?)[^>]*?>"; //图片链接地址
//        String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
//        p_image = Pattern.compile
//                (regEx_img, Pattern.CASE_INSENSITIVE);
//        m_image = p_image.matcher(htmlStr);
//        while (m_image.find()) {
//            // 得到<img />数据
//            img = m_image.group();
//            // 匹配<img>中的src数据
//            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
//            while (m.find()) {
//                pics.add(m.group(1));
//            }
//        }
//        return pics;
//    }

    /**
     * 创建目标路径所涉及到的目录，即/home/work/rhyme/xxx.jpg, 那么 home work rhyme 这三个文件夹都得自动创建
     *
     * @param targetAddr 创建相对路径
     */
    private static void makeDirPath(String targetAddr) {
        String realFileParentPath = PathUtil.getImgBasePath() + targetAddr;
        File dirPath = new File(realFileParentPath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
    }
}
